package game.module.nn.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.QipaiDataManager;
import game.module.nn.bean.NnRoom;
import game.module.nn.logic.NnDataManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageNn.C2SNnForceDismisroom;
import lua.LuaMessageNn.PushNnForceDismissRoom;

//@MsgCodeAnn(msgcode = C2SNNDismissRoom.id, accessLimit = 500)
@MsgCodeAnn(msgcode = C2SNnForceDismisroom.id, accessLimit = 500)
public class NnDismissRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(NnDismissRoomProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		int playerId = hero.getId();
		logger.info("nn dismiss room,playeyId={}", playerId);
		// 是否在房间中
		boolean isInRoom = NnDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is room exist
		NnRoom ddzRoom = NnDataManager.getInstance().getNnRoomByPlayerId(playerId);
		if (ddzRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		List<Integer> playerIdList = ddzRoom.getPlayerList();
		PushNnForceDismissRoom pushMsg = new PushNnForceDismissRoom();
		pushMsg.player_index = (byte) playerIdList.indexOf(playerId);
		// is room master -2017年8月18日 解除房主校验
		if (ddzRoom.getPlayerList().get(0) != playerId) {
			Integer play = new Integer(playerId);
			
			for (Integer aPlayerId : playerIdList) {
				PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
				if (pr != null && pr.isChannelActive()) {
					pr.writeAndFlush(pushMsg.build(pr.alloc()));
				}
			}
			playerIdList.remove(play);
			NnDataManager.getInstance().removePlayer(play);
			return; // 移除退出房间的玩家
		}
		for (Integer aPlayerId : playerIdList) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
		// do
		NnDataManager.getInstance().removeRoom(ddzRoom.getUuid());
		QipaiDataManager.getInstance().removeRoomUuid(ddzRoom.getUuid());
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// null
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// null
	}

}
